#!/bin/bash
if [[ $# -ne 2 ]]; then
    echo "The format is as follows:"
    echo "bash build.sh buildpath installpath"
    echo ":param buildpath: 应用构建绝对路径"
    echo ":param installpath: 应用安装绝对路径"
    exit 1
fi

[[ ! "$1" =~ ^/.* || "$1" = "/" ]] &&  echo "请输入正确的构建路径" && exit 1
[[ ! "$2" =~ ^/.* || "$2" = "/" ]] &&  echo "请输入正确的安装路径" && exit 1

create_dir()
{
    local path=$1
    [[ "$path" =~ .*/$ ]] && path=${path%/*}
    if [[ ! -d "$path" && ! -f "$path" ]]; then mkdir -p $path; else path=$path`date "+%y%m%d%H%M%S"` && mkdir -p $path; fi
    echo $path
}

buildpath=$(create_dir $1)
installpath=$(create_dir $2)

yum install -y m4 environment-modules systemd-devel \
xz-devel ncurses-devel numpy zlib-devel bzip2-devel lz4-devel Cython autoconf automake libcurl-devel openssl-devel 
source /etc/profile
module purge

set -e
dep_dir="dependency"

bash $dep_dir/bisheng-compiler-2.1.0.sh $buildpath $installpath
module use $installpath/bisheng-compiler-2.1.0
module load $installpath/bisheng-compiler-2.1.0/bisheng_modulefiles

export CC=clang
export CXX=clang++
export FC=flang

bash $dep_dir/samtools-1.15.1.sh $buildpath $installpath
module use $installpath/samtools-1.15.1
module load $installpath/samtools-1.15.1/samtools_modulefiles

bash $dep_dir/samblaster-0.1.26.sh $buildpath $installpath
module use $installpath/samblaster-0.1.26
module load $installpath/samblaster-0.1.26/samblaster_modulefiles

bash $dep_dir/ldc2-1.15.0.sh $buildpath $installpath
module use $installpath/ldc2-1.15.0
module load $installpath/ldc2-1.15.0/ldc2_modulefiles

bash $dep_dir/sambamba-0.8.2.sh $buildpath $installpath
module use $installpath/sambamba-0.8.2
module load $installpath/sambamba-0.8.2/sambamba_modulefiles

bash $dep_dir/pysam-0.19.0.sh $buildpath $installpath
module use $installpath/pysam-0.19.0
module load $installpath/pysam-0.19.0/pysam_modulefiles

bash lumpy-0.3.1.sh $buildpath $installpath

mkdir -p pkg/lumpy-0.3.1-hpc && cp -r $installpath/* pkg/lumpy-0.3.1-hpc/
cat>"pkg/lumpy-0.3.1-hpc/run.sh"<<EOF
#!/bin/bash
yum install -y m4 environment-modules systemd-devel csh time patch libatomic perl-Data-Dumper \\
autoconf automake libtool numactl binutils valgrind flex wget tar libatomic gcc-c++ git \\
xz-devel ncurses-devel numpy zlib-devel bzip2-devel lz4-devel Cython autoconf automake libcurl-devel openssl-devel
pip install pysam -i https://pypi.tuna.tsinghua.edu.cn/simple
source /etc/profile &> /dev/null 
current_dir="\$(cd "\$(dirname "\${BASH_SOURCE[0]}")" && pwd -P)"
for f in "\${current_dir}"/*; do
  if [[ -d "\${f}" && -f "\$(ls "\${f}"/*modulefiles 2>&1)" ]]; then
    module use "\${f}" && module load "\${f}"/*modulefiles
  fi
done
echo -e "\033[1;32;1mLumpy environment initialization completed.\033[0m"

EOF
cd pkg/ && tar zcvf lumpy-0.3.1-hpc.tar.gz lumpy-0.3.1-hpc

rm -rf $buildpath $installpath
